import json
import subprocess
import sys

from config import config

class Crypt:
    def __init__(self):
        self.data: bytes

        if not config["gpg_key"]:
            print("Crypt: Not Found `gpg_key`.", file=sys.stderr)
            sys.exit()

    def load_data(self, data):
        self.data = data

    def load_file(self, path):
        self.data = open(path, "rb").read()

    def decrypt_file(self, path) -> bytes:
        self.load_file(path)
        return self.decrypt()

    def encrypt_file(self, path):
        open(path, "wb").write(self.encrypt())

    def decrypt(self) -> bytes:
        gpg = subprocess.Popen( ['/usr/bin/gpg', '-dq'],
                                    stdin=subprocess.PIPE,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE
                                    )

        output_data, error = gpg.communicate(input=self.data)

        if not error:
            self.data = output_data
            return output_data
        else:
            print(f"Crypt: gpg_decrypt `{error.decode()}`.", file=sys.stderr)
            sys.exit(1)

    def encrypt(self) -> bytes:
        if config["gpg_key"]:
            gpg = subprocess.Popen( ['/usr/bin/gpg', '-r', f'{config["gpg_key"]}', f'-eq'],
                                        stdin=subprocess.PIPE,
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE
                                        )

            output_data, error = gpg.communicate(input=self.data)

            if not error:
                self.data = output_data
                return output_data
            else:
                print(f"Crypt: gpg_encrypt `{error.decode()}`.", file=sys.stderr)
                sys.exit(1)


    def get_data(self) -> bytes:
        return self.data



